package com.example.administrator.myapplication.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.easemob.EMCallBack;
import com.easemob.chat.EMChat;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMMessage;
import com.easemob.chat.TextMessageBody;
import com.example.administrator.myapplication.R;
import com.example.administrator.myapplication.adapter.ChatAdapter;
import com.sv.svbind.annotation.Bind;
import com.sv.svbind.context.AppActivity;

import java.util.ArrayList;
import java.util.List;

@Bind(layout = R.layout.activity_e)
public class ChatActivity extends AppActivity {


    @Bind(id = R.id.chat_content_lv)
    private ListView contentlv;
    @Bind(id = R.id.chat_content_et)
    private EditText contentEt;
    @Bind(id = R.id.chat_record)
    private ImageView recordImg;
    @Bind(id = R.id.back_ll_l)
    private LinearLayout back;

    private ChatAdapter chatAdapter;
    private List<EMMessage> beanList;
    private NewMessageBroadcastReceiver msgReceiver;
    private int sendFlag;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        initView();
        messageData();
        initEvent();
    }

    private void initView() {
        if (beanList==null){
            beanList=new ArrayList<>();
        }else {
            beanList.clear();
        }
    }


    private void messageData() {

        contentlv.setDividerHeight(0);
        chatAdapter=new ChatAdapter(ChatActivity.this, beanList);
        contentlv.setAdapter(chatAdapter);
        //步骤二：将创建的广播进行注册
        msgReceiver = new NewMessageBroadcastReceiver();
        IntentFilter intentFilter = new IntentFilter(EMChatManager.getInstance().getNewMessageBroadcastAction());
        intentFilter.setPriority(3);
        registerReceiver(msgReceiver, intentFilter);
        //步骤三：初始化，放置漏接新消息
        EMChat.getInstance().setAppInited();
    }

    private void initEvent() {
        recordImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initData();
                if (sendFlag == 1) {
                    sendMessage(contentEt.getText().toString());
                }
            }
        });
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    private void sendMessage(String content) {
        //获取到与聊天人的会话对象。参数username为聊天人的userid或者groupid，后文中的username皆是如此
        //EMConversation conversation = EMChatManager.getInstance().getConversation(username);
        //创建一条文本消息
        EMMessage message = EMMessage.createSendMessage(EMMessage.Type.TXT);
        //如果是群聊，设置chattype,默认是单聊
        //message.setChatType(EMMessage.ChatType.GroupChat);
        //设置消息body
        TextMessageBody txtBody = new TextMessageBody(content);
        message.addBody(txtBody);
        //设置接收人
        message.setReceipt("secondUser");
        //把消息加入到此会话对象中
        //conversation.addMessage(message);

        //发送消息
        EMChatManager.getInstance().sendMessage(message, new EMCallBack() {

            @Override
            public void onSuccess() {

            }

            @Override
            public void onError(int i, String s) {

            }

            @Override
            public void onProgress(int i, String s) {

            }
        });
        //将发送的消息加入集合
        beanList.add(message);
        chatAdapter.notifyDataSetChanged();
        contentlv.setSelection(beanList.size()-1);
        contentEt.setText("");
    }

    private void initData() {
        if (!TextUtils.isEmpty(contentEt.getText().toString())) {
            recordImg.setImageResource(R.mipmap.aliwx_reply_bar_text_normal);
            sendFlag = 1;
        } else {
            recordImg.setImageResource(R.mipmap.aliwx_reply_bar_record_normal);
            sendFlag = 0;
        }
    }

    /**
     * 接收消息的BroadcastReceiver
     *
     */
    private class NewMessageBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            //消息id
            String msgId = intent.getStringExtra("msgid");
            //发消息的人的username(userid)
            String msgFrom = intent.getStringExtra("from");
            //消息类型，文本，图片，语音消息等,这里返回的值为msg.type.ordinal()。
            //所以消息type实际为是enum类型
            int msgType = intent.getIntExtra("type", 0);
            Log.i("ddd", "new message id:" + msgId + " from:" + msgFrom + " type:" + msgType);
            //更方便的方法是通过msgId直接获取整个message
            EMMessage message = EMChatManager.getInstance().getMessage(msgId);


            Log.i("ddd","--->"+beanList.size());
            beanList.add(message);
            chatAdapter.notifyDataSetChanged();
            contentlv.setSelection(beanList.size()-1);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (msgReceiver != null) {
            unregisterReceiver(msgReceiver);
        }
    }
}
